﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Designtime.Metadata;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.Designer.Views
{
    public static class CheckOutThread
    {
        private static bool s_isRunning = false;
        private static Thread s_thread;
        private static Action<Guid, string, int, int> s_progress;
        private static Action<bool, int, int> s_completed;
        private static List<SolutionTreeViewNode> s_nodeList;

        /// <summary>
        /// solutiontreeviewNode状态在线程中修改
        /// </summary>
        /// <param name="nodeList"></param>
        /// <param name="progress">项目ID, 项目名称，签入进度，总数量</param>
        /// <param name="completed">是否出现错误，成功数量，总数量</param>
        public static bool Start(List<SolutionTreeViewNode> nodeList, Action<Guid, string, int, int> progress, Action<bool, int, int> completed)
        {
            if (s_isRunning)
            {
                return false;
            }

            s_nodeList = nodeList;
            s_progress = progress;
            s_completed = completed;
            s_isRunning = true;
            s_thread = new Thread(Running);
            s_thread.Start();
            return true;
        }

        public static void Stop()
        {
            if (s_isRunning)
            {
                s_thread.Abort();
                s_isRunning = false;
                s_thread = null;
            }
        }

        private static void Running()
        {
            int total = s_nodeList.Count;
            int progress = 0;
            bool hasError = false;

            CPPEI.Coolzon.ServiceProxy.DesignServiceRef.DesignServiceClient dsClient =
                CPPEI.Coolzon.ServiceProxy.DesignServiceProxyManager.Create();

            string workspacePath = UIContext.Current.LocalWorkSpace.LocalPath;
            Guid solutionId = UIContext.Current.CurrentSolution.ID;
            //检查服务器给的项目是否在本地都有，或者是否最新
            for (int index = 0; index < s_nodeList.Count; index++)
            {
                SolutionTreeViewNode tvNode = s_nodeList[index];

                VSFile vsFile = VSFileMgr.GetFileWithDefault(workspacePath, solutionId, tvNode.ID);

                if (vsFile.Action == VSFileAction.None)
                {
                    //文件处于签入状态
                    CPPEI.Coolzon.ServiceProxy.DesignServiceRef.GetLatestVersionRequest request = new CPPEI.Coolzon.ServiceProxy.DesignServiceRef.GetLatestVersionRequest();
                    request.Id = tvNode.ID;
                    request.SolutionId = solutionId;
                    request.Token = UIContext.Current.Token;

                    CPPEI.Coolzon.ServiceProxy.DesignServiceRef.GetLatestVersionResponse response = dsClient.GetLatestVersion(request);
                    if (vsFile == null || response.ItemVersion > vsFile.Version)
                    {
                        Logger.ErrorToTag(Library.LogTAG, string.Format("签出Name:{0},Id:{1}失败,服务器存在新版本", tvNode.Name, tvNode.ID));
                        System.Windows.Application.Current.Dispatcher.Invoke(() => { Coolzon.UI.CustomMessageBox.ShowError(string.Format("签出Name:{0}失败,服务器存在新版本", tvNode.Name)); });
                        hasError = true;
                        break;
                    }

                    CPPEI.Coolzon.ServiceProxy.DesignServiceRef.CheckOutRequest checkOutRequest = new ServiceProxy.DesignServiceRef.CheckOutRequest();
                    checkOutRequest.Token = UIContext.Current.Token;
                    checkOutRequest.SolutionId = solutionId;
                    checkOutRequest.Id = tvNode.ID;
                    checkOutRequest.WorkSpaceId = UIContext.Current.LocalWorkSpace.Id;
                    try
                    {
                        CPPEI.Coolzon.ServiceProxy.DesignServiceRef.ServiceResult result = dsClient.CheckOut(checkOutRequest);
                        if (result.IsSuccess)
                        {
                            tvNode.NodeStatus = NodeStatus.CheckOut;

                            // 更新本地的文件项目状态
                            VSFileMgr.GoToCheckOut(workspacePath, solutionId, tvNode.ID);

                            progress++;

                            s_progress(tvNode.ID, tvNode.Name, progress, total);
                        }
                        else
                        {
                            tvNode.NodeStatus = NodeStatus.OthersLocked;

                            // 更新本地的文件项目状态
                            VSFileMgr.GoToOthersLocked(workspacePath, solutionId, tvNode.ID);

                            Logger.ErrorToTag(Library.LogTAG, string.Format("签出Name:{0},Id:{1}失败", tvNode.Name, tvNode.ID));
                            hasError = true;
                            System.Windows.Application.Current.Dispatcher.Invoke(() => { Coolzon.UI.CustomMessageBox.ShowError(result.Message); });
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorToTag(Library.LogTAG, string.Format("签出Name:{0},Id:{1}失败,ex:{2}", tvNode.Name, tvNode.ID, ex));
                        hasError = true;
                        System.Windows.Application.Current.Dispatcher.Invoke(() => { Coolzon.UI.CustomMessageBox.ShowError("签出失败，" + ex.Message); });
                        break;
                    }
                }
                else
                {
                    progress++;

                    s_progress(tvNode.ID, tvNode.Name, progress, total);

                    Logger.ErrorToTag(Library.LogTAG, string.Format("签出Name:{0},Id:{1}成功，文件不处于签入状态", tvNode.Name, tvNode.ID));
                }
            }

            dsClient.Close();

            s_completed(hasError, progress, total);
            s_isRunning = false;
            s_thread = null;
        }
    }
}
